//  this library.
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/model/industry/category_model.dart';
import 'package:hktk_app/pages/select/select_subject_page.dart';
import 'package:hktk_app/util/data_util.dart';

import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/select/exam_label_widget.dart';
import 'package:hktk_app/widget/select/select_title_widget.dart';

/// 选择类型页面
class SelectTypePage extends StatefulWidget {
  /// 考试id，暂时传假名称模拟
  final String examId;

  /// 对应的科目相关数据
  final List<CategoryModel> subjectList;

  /// 已购买的章节id集合
  final List<CategoryModel>? buyCategorys;

  /// 是否跳转首页
  final int pageIndex;

  const SelectTypePage({
    super.key,
    required this.examId,
    required this.subjectList,
    this.buyCategorys,
    required this.pageIndex,
  });

  @override
  State createState() => _SelectTypePageState();
}

class _SelectTypePageState extends State<SelectTypePage> {
  /// 上下文控制器
  late BuildContext _context;

  /// 搜索对应方法
  late String _searchKey;

  /// 已购买的科目id
  late List<int> _buyIds;

  @override
  void initState() {
    super.initState();

    _searchKey = "";
    _buyIds = [];
    if (widget.buyCategorys != null) {
      _buyIds = widget.buyCategorys!
          .map((CategoryModel category) => category.parentId ?? 0)
          .toList();
    }
  }

  @override
  void dispose() {
    super.dispose();

    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {

    _context = context;
    // 获取安全边距

    return Scaffold(
      backgroundColor: colorWhite1,
      body: Container(
        padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight, bottom:  ScreenUtil().bottomBarHeight),
        child: Column(
          children: [
            SelectTitleWidget(
                pageContext: context,
                titleName: "选择类型",
                onSubmittedFun: _searchType),
            Expanded(child: _typeItems(context)),
          ],
        ),
      ),
    );
  }

  /// 选择类型搜索方法
  _searchType(String value) {
    setState(() {
      _searchKey = value;
    });
  }

  /// 显示数据
  _typeItems(BuildContext context) {
    // 获取安全边距
    return Container(
      padding: EdgeInsets.fromLTRB(30, 0, 30, ScreenUtil().bottomBarHeight + 30),
      child: MediaQuery.removePadding(
        removeTop: true,
        context: context,
        child: GridView.count(
          padding: EdgeInsets.only(top: 30),
          crossAxisCount: 3,
          childAspectRatio: 213 / 72,
          mainAxisSpacing: 30,
          crossAxisSpacing: 20,
          children: _searchItems(),
        ),
      ),
    );
  }

  /// 本地搜索相关数据展示
  _searchItems() {
    List<Widget> widgets = [];
    for (CategoryModel model in widget.subjectList) {
      if (_searchKey != "") {
        if (model.name!.contains(_searchKey)) {
          widgets.add(_typeItem(model));
        }
      } else {
        widgets.add(_typeItem(model));
      }
    }
    return widgets;
  }

  /// 显示对应item
  Widget _typeItem(CategoryModel model) {
    return GestureDetector(
      onTap: () {

        _typeItemOnTap(model.id!);
      },
      child: ExamLabelWidget.category(
        text: model.name!,
        showBuy: _getShowByu(model),
      ),
    );
  }

  /// 计算是否显示已购标签方法
  _getShowByu(CategoryModel model) {
    if (widget.buyCategorys == null) {
      return false;
    }
    return _buyIds.contains(model.id);
  }

  /// 对应item点击方法
  void _typeItemOnTap(int parentId) {
    // 开启加载框
    ToastUtil.loadingBoxShow(_context);
    // 加载数据
    IndustryDao.leafList(
      examId: widget.examId,
      parentId: parentId,
    ).then((value) {
      ToastUtil.loadingBoxRemove();
      if (value == null || value.isEmpty) {
        ToastUtil.show(context: _context, msg: "暂无数据");
      } else {
        CategoryModel model2 = value[0];
        var attribute = model2.attribute!;
        var i = attribute & 1;
        var j = attribute & 0;



        if (i == 1) {
          // 应该设置当前科目的id 保存选中科目
          dataUtilComm.dataModel.categoryId = model2.id!;
          IndustryDao.saveCategoryModels([model2]);
          IndustryDao.saveSelectCategoryId(0);
          // 最后一级，跳转选择科目页面
          Navigator.pushNamed(context, "/select-category",arguments: {
            "subjectList": value,
            "buyCategorys": widget.buyCategorys,
            "pageIndex": widget.pageIndex,
            "pageName":"/tab"
          });
        } else if (j == 0) {
          // 不是最后一级，跳转选择类型页面
          Navigator.pushNamed(context, "/select-type",arguments: {
            "examId": widget.examId,
            "subjectList": value,
            "buyCategorys": widget.buyCategorys,
            "pageIndex": widget.pageIndex,
          });
        }
      }
    }).catchError((e) {
      ToastUtil.loadingBoxRemove();

      String msg = "未知错误，请重试";
      if (e is DaoException) {

        msg = e.msg;
      }
      ToastUtil.show(context: _context, msg: msg);
    });
  }
}
